package com.xjmall.controller.background;

import com.google.common.collect.Maps;
import com.xjmall.common.Const;
import com.xjmall.common.ServerResult;
import com.xjmall.exception.AuthorityException;
import com.xjmall.exception.NotLoginException;
import com.xjmall.pojo.User;
import com.xjmall.service.IFileService;
import com.xjmall.util.PropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 后台通用Controller
 * Created by An on 2017/8/26.
 */
@Controller
@RequestMapping("/manage/common")
public class CommonController {

    @Autowired
    private IFileService iFileService;

    /**
     * 上传图片
     * @param session 当前会话
     * @param file 要上传的文件
     * @param request HttpServletRequest
     * @return ServerResult
     */
    @RequestMapping(value = "upload.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResult upload(HttpSession session, @RequestParam(value = "upload_file", required = false) MultipartFile file, HttpServletRequest request) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            throw new NotLoginException("用户未登录，拒绝访问");
        }
        // 校验用户是否为管理员
        if (user.getRole() != Const.Role.ROLE_ADMIN) {
            throw new AuthorityException("无操作权限");
        }
        // 调用业务层接口执行操作
        String path = request.getSession().getServletContext().getRealPath("upload");
        String targetFileName = iFileService.upload(file, path);
        Map<String, String> fileMap = Maps.newHashMap();
        fileMap.put("uri", targetFileName);
        fileMap.put("imageHost", PropertiesUtil.getProperty("ftp.server.http.prefix", "http://127.0.0.1/"));
        return ServerResult.successData(fileMap);
    }
}
